# coding=gbk
"""
Created on 2016/6/23 0023

@author: Blunce

@about:

"""
import matplotlib.pyplot as plt
import numpy as np
from utils.myUtils import save_as_csv
import os


class BMC:
    def __init__(self, iteration=14, p=0.4, qs=np.arange(-10, 10.5, 0.5)):
        self.__iteration = iteration
        self.__p = p
        self.__Q = qs
        self.__x = [1]
        self.__A = []
        self.__F = []

    def process(self):
        for i in range(self.__iteration):
            self.__x = self.__segment(self.__x, self.__p)
        return self.__x

    def __segment(self, x, p):
        tmp = []
        for one in x:
            tmp.append(one * p)
            tmp.append(one * (1 - p))
        return np.array(tmp)

    def drawDataLine(self):
        plt.title("Binomial Multiplicative Cascades")
        plt.plot(self.__x)
        plt.show()

    def getSpectrum(self):
        for one in self.__Q:
            tmp_p1, tmp_p2 = self.__p ** one, (1 - self.__p) ** one
            self.__A.append(-(tmp_p1 * np.log2(self.__p) +
                              tmp_p2 * np.log2(1 - self.__p)) /
                            (tmp_p1 + tmp_p2))
            self.__F.append(
                np.log2(tmp_p1 + tmp_p2) - one * (
                    tmp_p1 * np.log2(self.__p) + tmp_p2 * np.log2(
                        1 - self.__p)) / (
                    tmp_p1 + tmp_p2))

        return np.array(self.__A), np.array(self.__F)

    def drawSpectrum(self):
        plt.title("Spectrum")
        plt.plot(self.__A, self.__F)
        plt.ylim(np.min(self.__F) - 0.1, np.max(self.__F) + 0.1)
        plt.show()

    def saveX(self):
        with open(os.getcwd()[
                  :-5] + "data" + os.sep + "bmc" + os.sep + "bmc.csv",
                  "w") as fw:
            X = self.__x * 10 ** 6
            for x in X:
                fw.write(str(x) + "\n")


if __name__ == '__main__':
    print "**************start**************\n\n"

    bmc = BMC()
    bmc.process()
    # bmc.drawDataLine()
    bmc.getSpectrum()
    bmc.drawSpectrum()
    # bmc.saveX()

    print "\n\n**************end**************"
